package com.cskt.shiro;

import com.cskt.common.constants.ErrorCodeEnum;
import com.cskt.common.exception.ServiceException;
import com.cskt.entity.User;
import com.cskt.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author mo
 * @Description: 自定义认证及鉴权处理器
 * @date 2020-09-22 15:13
 */

public class MyRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    /**
     * 此期没有涉及到用户的角色，所只不需要实现鉴权
     * @param
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 怎
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String jwtToken=(String) authenticationToken.getCredentials();
        if (jwtToken == null) {
            throw new ServiceException(ErrorCodeEnum.AUTH_TOKEN_IS_EMPTY);
        }

        String username = JwtUtil.getUsername(jwtToken);
        if (username == null) {
            throw new ServiceException(ErrorCodeEnum.AUTH_UNKNOWN);
        }
        //根据传递过来的Username，也就是userCode查询用户信息
        User user = userService.findUserByUserCode(username);
        if (user == null) {
            throw new
                    ServiceException(ErrorCodeEnum.AUTH_AUTHENTICATION_FAILED);
        }
        if (!JwtUtil.verify(jwtToken, username, user.getUserPassword())) {
            //当用户名和密码验证不通过
            throw new
                    ServiceException(ErrorCodeEnum.AUTH_AUTHENTICATION_FAILED);

        }

        return new SimpleAuthenticationInfo(jwtToken,jwtToken,"my_realm");
    }
}
